package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizErrorCode;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

@RestControllerAdvice
@Slf4j
public class MyExceptionHandle {


    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R vlaidExceptionHandle(MethodArgumentNotValidException methodArgumentNotValidException){
        BindingResult bindingResult = methodArgumentNotValidException.getBindingResult();
        HashMap<String, String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((item)->{
            String field = item.getField();
            String defaultMessage = item.getDefaultMessage();
            errorMap.put(field,defaultMessage);
        });
        return R.error(BizErrorCode.VALID_EXCEPTION.getCode(),BizErrorCode.VALID_EXCEPTION.getMessage()).put("data",errorMap);
    }

    @ExceptionHandler(Exception.class)
    public R fullExceotion(Exception exception){
        log.info("异常原因:",exception);
        return R.error(BizErrorCode.UNKNOWN_EXCEPTION.getCode(),BizErrorCode.UNKNOWN_EXCEPTION.getMessage());
    }






}
